import { Repository } from 'typeorm';
import { AppDataSource } from '../../config/database';
import { ContentDisplay, ContentCategory, ContentType } from '../../entities/ContentDisplay';

export class ContentDisplayService {
  private contentDisplayRepository: Repository<ContentDisplay>;

  constructor() {
    this.contentDisplayRepository = AppDataSource.getRepository(ContentDisplay);
  }

  /**
   * 获取展示内容列表
   */
  async getContentList(query: any = {}): Promise<{ contents: ContentDisplay[]; total: number }> {
    const { page = 1, pageSize = 10, category, type, isActive, title } = query;
    
    const queryBuilder = this.contentDisplayRepository.createQueryBuilder('content');
    
    // 添加模块分类过滤
    if (category !== undefined) {
      queryBuilder.andWhere('content.category = :category', { category });
    }
    
    // 添加内容类型过滤
    if (type !== undefined) {
      queryBuilder.andWhere('content.type = :type', { type });
    }
    
    // 添加状态过滤
    if (isActive !== undefined) {
      queryBuilder.andWhere('content.isActive = :isActive', { isActive });
    }
    
    // 添加标题搜索
    if (title) {
      queryBuilder.andWhere('content.title LIKE :title', { title: `%${title}%` });
    }
    
    // 排序：按排序号升序，创建时间倒序
    queryBuilder.orderBy('content.sortOrder', 'ASC')
      .addOrderBy('content.createTime', 'DESC');
    
    // 分页
    const total = await queryBuilder.getCount();
    const contents = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getMany();

    return { contents, total };
  }

  /**
   * 获取展示内容详情
   */
  async getContentById(id: string): Promise<ContentDisplay | null> {
    return await this.contentDisplayRepository.findOne({ where: { id } });
  }

  /**
   * 创建展示内容
   */
  async createContent(contentData: Partial<ContentDisplay>, userId: string): Promise<ContentDisplay> {
    const content = this.contentDisplayRepository.create({
      ...contentData,
      createBy: userId,
      updateBy: userId
    });
    
    return await this.contentDisplayRepository.save(content);
  }

  /**
   * 更新展示内容
   */
  async updateContent(id: string, contentData: Partial<ContentDisplay>, userId: string): Promise<ContentDisplay | null> {
    const content = await this.getContentById(id);
    
    if (!content) {
      return null;
    }
    
    Object.assign(content, {
      ...contentData,
      updateBy: userId
    });
    
    return await this.contentDisplayRepository.save(content);
  }

  /**
   * 删除展示内容
   */
  async deleteContent(id: string): Promise<boolean> {
    try {
      const result = await this.contentDisplayRepository.delete(id);
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('删除展示内容失败:', error);
      return false;
    }
  }

  /**
   * 更新内容状态
   */
  async updateContentStatus(id: string, isActive: boolean, userId: string): Promise<boolean> {
    try {
      const result = await this.contentDisplayRepository.update(
        { id },
        { 
          isActive,
          updateBy: userId,
          updateTime: new Date()
        }
      );
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('更新内容状态失败:', error);
      return false;
    }
  }

  /**
   * 更新内容排序
   */
  async updateContentSort(id: string, sortOrder: number, userId: string): Promise<boolean> {
    try {
      const result = await this.contentDisplayRepository.update(
        { id },
        { 
          sortOrder,
          updateBy: userId,
          updateTime: new Date()
        }
      );
      return result.affected ? result.affected > 0 : false;
    } catch (error) {
      console.error('更新内容排序失败:', error);
      return false;
    }
  }

  /**
   * 根据模块类型获取内容列表（前台接口）
   */
  async getContentsByCategory(category: ContentCategory, limit: number = 10): Promise<ContentDisplay[]> {
    return await this.contentDisplayRepository.find({
      where: {
        category,
        isActive: true
      },
      order: {
        sortOrder: 'ASC',
        createTime: 'DESC'
      },
      take: limit
    });
  }
}

export const contentDisplayService = new ContentDisplayService(); 